<template>
  <div class="address-page">
    <!-- 导航栏 -->
    <van-nav-bar
      title="收货地址"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 地址列表 -->
    <div class="address-list">
      <div v-for="item in addressList" :key="item.addr_id" class="address-item">
        <div class="address-info" @click="onEdit(item)">
          <div class="user-info">
            <span class="name">{{ item.consignee }}</span>
            <span class="phone">{{ item.mobile }}</span>
            <van-tag type="primary" size="small" v-if="item.is_default === 1">默认</van-tag>
          </div>
          <div class="address-detail">
            {{ item.province }}{{ item.city }}{{ item.area }}{{ item.addr }}
          </div>
        </div>
        <van-icon name="arrow" class="arrow-icon" />
      </div>
      
      <!-- 空状态 -->
      <div v-if="!addressList.length" class="empty-state">
        <van-empty description="暂无收货地址" />
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-button">
      <van-button type="primary" block round @click="onAdd">
        新增收货地址
      </van-button>
    </div>

    <!-- 编辑弹窗 -->
    <van-popup v-model:show="showEdit" position="bottom" round>
      <div class="popup-content">
        <div class="popup-header">
          <span>{{ currentAddress.addr_id ? '编辑地址' : '新增地址' }}</span>
          <van-icon name="cross" @click="showEdit = false" />
        </div>
        <div class="popup-body">
          <van-form @submit="onSubmit">
            <van-cell-group inset>
              <van-field
                v-model="form.consignee"
                name="consignee"
                label="收货人"
                placeholder="请输入收货人姓名"
                :rules="[{ required: true, message: '请输入收货人姓名' }]"
              />
              <van-field
                v-model="form.mobile"
                name="mobile"
                label="手机号"
                placeholder="请输入手机号"
                :rules="[{ required: true, message: '请输入手机号' }]"
              />
              <van-field
                v-model="form.province"
                name="province"
                label="省份"
                placeholder="请输入省份"
                :rules="[{ required: true, message: '请输入省份' }]"
              />
              <van-field
                v-model="form.city"
                name="city"
                label="城市"
                placeholder="请输入城市"
                :rules="[{ required: true, message: '请输入城市' }]"
              />
              <van-field
                v-model="form.area"
                name="area"
                label="区域"
                placeholder="请输入区域"
                :rules="[{ required: true, message: '请输入区域' }]"
              />
              <van-field
                v-model="form.addr"
                name="addr"
                label="详细地址"
                type="textarea"
                rows="2"
                autosize
                placeholder="请输入详细地址"
                :rules="[{ required: true, message: '请输入详细地址' }]"
              />
              <van-field
                v-model="form.post_code"
                name="post_code"
                label="邮编"
                placeholder="请输入邮编（选填）"
              />
              <van-field name="is_default" label="设为默认地址">
                <template #input>
                  <van-switch 
                    v-model="form.is_default" 
                    :active-value="1" 
                    :inactive-value="0"
                    :disabled="currentAddress.addr_id && currentAddress.is_default === 1"
                    @change="onDefaultChange"
                  />
                </template>
              </van-field>
            </van-cell-group>
            
            <div class="form-buttons">
              <van-button round block type="primary" native-type="submit">
                保存
              </van-button>
              <template v-if="currentAddress.addr_id">
                <van-button 
                  round 
                  block 
                  type="danger" 
                  @click="onDelete"
                  style="margin-top: 12px;"
                >
                  删除
                </van-button>
              </template>
            </div>
          </van-form>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { getAddressList, saveAddress, deleteAddress, setDefaultAddress, updateAddress } from '@/api/user/user'

const router = useRouter()
const addressList = ref([])
const showEdit = ref(false)
const currentAddress = ref({})
const form = ref({
  consignee: '',
  mobile: '',
  province: '',
  city: '',
  area: '',
  addr: '',
  post_code: '',
  is_default: 0,
  lng: 0,
  lat: 0
})

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 获取地址列表
const loadAddressList = async () => {
  try {
    const userId = JSON.parse(sessionStorage.getItem('user')).id
    const res = await getAddressList(userId)
    if (res.code === 200) {
      addressList.value = res.data || []
    }
  } catch (error) {
    showToast('获取地址列表失败')
  }
}

// 添加新地址
const onAdd = () => {
  currentAddress.value = {}
  form.value = {
    consignee: '',
    mobile: '',
    province: '',
    city: '',
    area: '',
    addr: '',
    post_code: '',
    is_default: 0,
    lng: 0,
    lat: 0
  }
  showEdit.value = true
}

// 编辑地址
const onEdit = (item) => {
  currentAddress.value = item
  form.value = { ...item }
  
  // 如果是默认地址，禁用切换
  if (item.is_default === 1) {
    form.value.is_default = 1
  }
  showEdit.value = true
}

// 删除地址
const onDelete = () => {
  showDialog({
    title: '提示',
    message: '确定要删除此地址吗？',
    showCancelButton: true
  }).then(async () => {
    try {
      const res = await deleteAddress(currentAddress.value.addr_id)
      if (res.code === 200) {
        showToast('删除成功')
        showEdit.value = false
        loadAddressList()
      }
    } catch (error) {
      showToast('删除失败')
    }
  })
}

// 提交表单
const onSubmit = async (values) => {
  try {
    const userId = JSON.parse(sessionStorage.getItem('user')).id
    const data = {
      ...values,
      user_id: userId,
    }
    
    let res
    if (currentAddress.value.addr_id) {
      // 更新地址
      data.addr_id = currentAddress.value.addr_id
      res = await updateAddress(data)
      
      // 如果设置为默认地址，需要调用设置默认地址接口
      if (data.is_default === 1 && currentAddress.value.is_default !== 1) {
        const oldDefaultAddr = addressList.value.find(item => item.is_default === 1)
        const oldAddrId = oldDefaultAddr ? oldDefaultAddr.addr_id : 0
        
        await setDefaultAddress({
          newAddr: data.addr_id,
          oldAddr: oldAddrId
        })
      }
    } else {
      // 新增地址
      res = await saveAddress(data)
      
      // 如果是第一个地址或设置为默认地址，需要调用设置默认地址接口
      if (data.is_default === 1 || addressList.value.length === 0) {
        const oldDefaultAddr = addressList.value.find(item => item.is_default === 1)
        const oldAddrId = oldDefaultAddr ? oldDefaultAddr.addr_id : 0
        
        await setDefaultAddress({
          newAddr: res.data, // 假设接口返回新地址的 ID
          oldAddr: oldAddrId
        })
      }
    }

    if (res.code === 200) {
      showToast('保存成功')
      showEdit.value = false
      loadAddressList()
    }
  } catch (error) {
    showToast('保存失败')
  }
}

// 监听默认地址切换
const onDefaultChange = async (value) => {
  if (value === 1) {
    // 找到当前的默认地址
    const oldDefaultAddr = addressList.value.find(item => item.is_default === 1)
    const oldAddrId = oldDefaultAddr ? oldDefaultAddr.addr_id : 0
    
    try {
      await setDefaultAddress({
        newAddr: currentAddress.value.addr_id,
        oldAddr: oldAddrId
      })
      loadAddressList() // 重新加载列表以更新状态
    } catch (error) {
      showToast('设置默认地址失败')
      form.value.is_default = 0 // 恢复状态
    }
  }
}

onMounted(() => {
  loadAddressList()
})
</script>

<style scoped>
.address-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 120px;
}

.address-list {
  padding: 12px;
}

.address-item {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.address-info {
  flex: 1;
  margin-right: 12px;
}

.user-info {
  margin-bottom: 8px;
}

.name {
  font-size: 16px;
  font-weight: 500;
  margin-right: 12px;
}

.phone {
  color: #666;
  margin-right: 8px;
}

.address-detail {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.arrow-icon {
  color: #999;
  font-size: 16px;
}

.bottom-button {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  padding: 16px;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.popup-content {
  padding-bottom: env(safe-area-inset-bottom);
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #f5f5f5;
}

.popup-header span {
  font-size: 16px;
  font-weight: 500;
}

.popup-header .van-icon {
  font-size: 20px;
  color: #999;
}

.popup-body {
  padding: 16px 0;
  max-height: 80vh;
  overflow-y: auto;
}

.form-buttons {
  margin: 24px 16px;
}

.empty-state {
  padding: 40px 0;
}
</style>